package com.ddf.jerry.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.HttpResponse;
import com.ddf.norman.util.StringUtil;
import com.ddf.pluto.controller.LoanController;
import com.ddf.publics.config.SmsConfig;
import com.ddf.publics.config.Utill;
import com.ddf.publics.entity.*;
import com.ddf.publics.service.*;
import com.ddf.publics.tool.Constant;
import com.ddf.publics.tool.MoneyFund;
import com.ddf.publics.utils.RedisUtil;
import com.ddf.publics.utils.VerificationCodeUtil;
import com.ddf.zero.controller.LoanHistoryController;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.security.provider.MD5;
import sun.security.rsa.RSASignature;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.security.Principal;
import java.util.*;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;

@Controller
public class AccountController {
    //用户
    @Resource
    private UserService userService;

    //用户信息
    @Resource
    private UserInfoService userInfoService;

    //银行卡
    @Resource
    private UserBankService userBankService;

    //资金记录
    @Resource
    private FundService fundService;

    //支付宝
    @Resource
    AlipayService alipayService;

    @Autowired
    private LoginService loginService;

    //QQ邮箱
    @Autowired
    JavaMailSenderImpl javaMailSender;
    //redis
    @Autowired
    RedisUtil redisUtil;
    //投资记录
    @Resource
    BidService bidService;

    @Autowired
    LoanApplicationService loanApplicationService;

    @Autowired
    LoanHistoryController loanHistoryController;

    @Autowired
    ZeroService zeroService;
    //判断交易密码
    @Resource
    PayPwdService payPwdService;

    @Autowired
    private VerificationCodeUtil verificationCodeUtil;
    /**
     * @description 个人中心总览主页
     * @author jerry
     * @date 2020/6/17 8:14
     * @params []
     * @return java.lang.String
     */
    @RequestMapping(value = "/userInfo")
    public String userInfo(Principal principal, Model model){
        User user = loginService.queryByPhone(principal.getName());
        UserInfo userInfo = userInfoService.userInfoList(user.getId());//资金

        AtomicReference<Float> loanmoney = new AtomicReference<>((float) 0);
        model.addAttribute("user",user);
        //可用余额
        model.addAttribute("userInfoMoney",userInfo.getMoney());
        DecimalFormat df = new DecimalFormat("#.00");
        //代收本息
        Float interest = bidService.interest(user.getId());
        model.addAttribute("interest",interest);

        //累积受益
        Float profit = bidService.profit(user.getId());
        model.addAttribute("profit",profit);

        //回款计划
        int page3 = bidService.totalRowsId3(user.getId());
        model.addAttribute("page3",page3);

        //资金记录
        int page = fundService.totalRowsId(user.getId());
        model.addAttribute("page",page);

        User user2 = userService.queryById(user.getId());
        model.addAttribute("user2",user2);
        model.addAttribute("userInfo",userInfo);

        //投资记录
        int page2 = bidService.totalRowsId3(user.getId());
        model.addAttribute("page2",page2);

        //待还借款
        List<LoanApplication> loanApplications = loanApplicationService.queryByUserId(user.getId());
        loanApplications.forEach((loanApplication)->{
            //查询出单个借贷信息
            LoanVo loanVo = zeroService.UserLoan(loanApplication.getLId());
            loanHistoryController.loanData(loanVo);
            loanmoney.updateAndGet(v -> new Float(v + (loanVo.getSurplus_money())));
        });
        try {
            model.addAttribute("loanmoney",String.format("%.2f",(loanmoney.toString())));
        }catch (IllegalFormatConversionException e){
            model.addAttribute("loanmoney",loanmoney);
        }
        return "userInfo/index";
    }
    /***
     * @description 资金记录
     * @author jerry
     * @date 2020/6/27 19:39
     * @params [uid, page, limit]
     * @return java.util.List<java.util.Map>
     */

    @RequestMapping("/fundPage")
    @ResponseBody
    public List<Map> fundPage(Integer uid, Integer page, Integer limit){
        if(page==null){
            page =1;
        }
        if(limit==null){
            limit=5;
        }
        int offset = (page-1)*limit;
        List<Map> funListUid =  fundService.funListUid(uid,offset,limit);
        return funListUid;
    }

    /**
     * @description 账户设置
     * @author jerry
     * @date 2020/6/17 8:14
     * @params []
     * @return java.lang.String
     */
    @GetMapping(value = "/userSet")
    public String userSet(Principal principal, Model model) {
        int userId = loginService.queryByPhone(principal.getName()).getId();//用户id

        User user = userService.queryById(userId);
        UserInfo userInfo = userInfoService.userInfoList(userId);

        String a = user.getPhone().substring(0,3);
        String b = user.getPhone().substring(7,user.getPhone().length()-0);
        String ab = a+"****"+b;
        model.addAttribute("phone",ab);
        if(user.getEmail() !=null && user.getEmail()!=""){
            String c = user.getEmail().substring(0,3);
            String d = user.getEmail().substring(7,user.getEmail().length()-0);
            String cd = c+"****"+d;
            model.addAttribute("email",cd);
        }

        if(userInfo.getIdCard() !=null && userInfo.getIdCard()!=""){
            String e = userInfo.getIdCard().substring(0,14);
            String f= e+"****";
            model.addAttribute("idCard",f);
        }
        if(userInfo.getPayPwd()!=null && userInfo.getPayPwd()!=""){
            String g = userInfo.getPayPwd().substring(0,2);
            String h = "******";
            model.addAttribute("payPwd",h);
        }

       if(userInfo.getRealName()!=null && userInfo.getRealName()!=""){
           String na = userInfo.getRealName().substring(0,userInfo.getRealName().length()-2);
           String name = na +"**";
           model.addAttribute("realName",name);
       }
        model.addAttribute("user",user);//用户
        model.addAttribute("userInfo",userInfo);
        return "userInfo/userSet";
    }
    
    /***
     * @description 上传头像
     * @author jerry
     * @date 2020/6/29 8:50
     * @params [file, principal]
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */

    @RequestMapping(value = "/uploadFace")
    @ResponseBody
    public Map<String,Object> uploadFace(@RequestParam(required=false) MultipartFile file, Principal principal) throws IOException {
        User user = loginService.queryByPhone(principal.getName());

        if (!file.isEmpty()) {
            //上传文件路径
           String path = "D:\\Temp\\imgs\\goods";
           String topPath = "goods/";

            //上传文件名
            String filename = file.getOriginalFilename();
            File filepath = new File(path, filename);

            //判断路径是否存在，没有就创建一个
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }

            //将上传文件保存到一个目标文档中
            File file1 = new File(path + File.separator + filename);
            user.setFace(topPath+filename);
            userService.update(user);
            file.transferTo(file1);
            Map<String,Object> res = new HashMap<>();
            //返回的是一个url对象
            res.put("url", topPath+filename);
            return res;

        } else {
            Map map = new HashMap();
            map.put("code","\"code\": 1");
            return map;
        }
    }

    /**
     * @description 更改昵称
     * @author jerry
     * @date 2020/6/17 14:41
     * @params
     * @return
     */
    @RequestMapping("/updateName")
    @ResponseBody
    public String updateName(int userId ,String Name){
        User user = new User();
        user.setId(userId);
        user.setNickName(Name);
        User user1 = userService.update(user);
        if(user1!=null){
            return "true";
        }else {
            return "false";
        }


    }

    /**
     * @description 投资记录
     * @author jerry
     * @date 2020/6/17 8:15
     * @params []
     * @return java.lang.String
     */
    @RequestMapping(value = "/depositsHistory")
    public String depositsHistory(Principal principal,Model model) {
        User user = loginService.queryByPhone(principal.getName());
        int offset = 0;
        int limit = 5;
        int page = bidService.totalRowsId(user.getId());
        int page2 = bidService.totalRowsId2(user.getId());
        model.addAttribute("page",page);
        model.addAttribute("page2",page2);

        List<Map> bidList =  bidService.bidListUid(user.getId(),offset,limit);

        model.addAttribute("userId",user.getId());
        model.addAttribute("bidList",bidList);
        return "userInfo/depositsHistory";
    }
    /***
     * @description 活期投资记录
     * @author jerry
     * @date 2020/6/28 20:12
     * @params [principal, model]
     * @return java.lang.String
     */
    @RequestMapping(value = "/depositsHistory2")
    public String depositsHistory2(Principal principal,Model model) {
        User user = loginService.queryByPhone(principal.getName());
        int offset = 0;
        int limit = 5;
        int page2 = bidService.totalRowsId2(user.getId());
        model.addAttribute("page2",page2);

        List<Map> bidList =  bidService.bidListUid2(user.getId(),offset,limit);

        model.addAttribute("userId",user.getId());
        model.addAttribute("bidList",bidList);
        return "userInfo/depositsHistory";
    }

    //点击下一页查询活期定期投资记录
    @RequestMapping("/investmentPage3")
    @ResponseBody
    public List<Map> investmentPage3(Integer uid, Integer page, Integer limit){
        if(page==null){
            page =1;
        }
        if(limit==null){
            limit=5;
        }
        int offset = (page-1)*limit;
        List<Map> bidList =  bidService.bidListUid3(uid,offset,limit);

        return bidList;
    }


    //点击下一页查询定期投资记录
    @RequestMapping("/investmentPage")
    @ResponseBody
    public List<Map> investmentPage(Integer uid, Integer page, Integer limit){
        if(page==null){
            page =1;
        }
        if(limit==null){
            limit=5;
        }
        int offset = (page-1)*limit;
        List<Map> bidList =  bidService.bidListUid(uid,offset,limit);

        return bidList;
    }

    //点击下一页查询活期投资记录
    @RequestMapping("/investmentPage2")
    @ResponseBody
    public List<Map> investmentPage2(Integer uid, Integer page, Integer limit){
        if(page==null){
            page =1;
        }
        if(limit==null){
            limit=5;
        }
        int offset = (page-1)*limit;
        List<Map> bidList =  bidService.bidListUid2(uid,offset,limit);

        return bidList;
    }

    /**
     * @description 充值
     * @author jerry
     * @date 2020/6/17 8:15
     * @params []
     * @return java.lang.String
     */
    @GetMapping(value = "/recharge")
    public String recharge( Principal principal, Model model) {
        int userId = loginService.queryByPhone(principal.getName()).getId();//用户id
        List<UserBank> userBanks =userBankService.queryAllByUID(userId);
        model.addAttribute("userBanks",userBanks);
        model.addAttribute("userId",userId);
        return "userInfo/recharge";
    }

    /***
     * @description 银行卡充值
     * @author jerry
     * @date 2020/6/18 20:45
     * @params [userId, money, uid]
     * @return java.lang.String
     */
    @RequestMapping("/bankRecharge/{userId}/{money}/{uid}")
    @ResponseBody
    public String bankRecharge(@PathVariable int userId,@PathVariable float money,@PathVariable int uid){
        UserInfo userInfo =  userInfoService.userInfoList(userId);
        userInfo.getPayPwd();
        if(userInfo.getPayPwd().equals("")||userInfo.getPayPwd()==null){
             return "1";
        }
        return "0";
    }
    
    /***
     * @description 查找银行卡
     * @author jerry
     * @date 2020/6/28 16:02
     * @params [principal]
     * @return java.lang.String
     */


    @RequestMapping("/czBank")
    @ResponseBody
    public String czBank(Principal principal){
        User user = loginService.queryByPhone(principal.getName());

        List<UserBank> userBanks = userBankService.queryAllByUID(user.getId());
        if(userBanks.size() !=0){
            return "1";
        }
        return "0";
    }



    /***
     * @description 验证交易密码
     * @author jerry
     * @date 2020/6/20 8:06
     * @params [userId, pwd, money]
     * @return java.lang.String
     */
    @RequestMapping("/payPwd/{userId}/{pwd}/{money}")
    @ResponseBody
    public String payPwd(@PathVariable int userId,@PathVariable String pwd,@PathVariable float money){
        int paystate = payPwdService.payPwd(userId, pwd);
        UserInfo userInfo=userInfoService.userInfoList(userId);
        switch (paystate){
            case Constant.PAY_LOCK:
                return "2";
            case Constant.PAY_NO:
                return "1";
        }

        userInfo.setMoney(userInfo.getMoney()+money);
        userInfoService.update(userInfo);
        //资金记录
        Fund fund = new Fund();
        fund.setFundAmunt(money);
        fund.setUId(userId);
        fund.setFundPost(MoneyFund.FUND_RECHARGE);//充值
        fundService.insert(fund);
        return "0";
    }


    /**
     * @description 提现
     * @author jerry
     * @date 2020/6/17 8:15
     * @params []
     * @return java.lang.String
     */
    @GetMapping(value = "/withdraw")
    public String withdraw(Principal principal, Model model) {
        User user = loginService.queryByPhone(principal.getName());
        model.addAttribute("user",user);

        List<UserBank> userBanks =userBankService.queryAllByUID(user.getId());
        model.addAttribute("userBanks",userBanks);

        UserInfo userInfo = userInfoService.userInfoList(user.getId());
        model.addAttribute("userInfo",userInfo);

        return "userInfo/withdraw";
    }

    /***
     * @description 确定提现
     * @author jerry
     * @date 2020/6/23 8:04
     * @params [userId, pwd, money]
     * @return java.lang.String
     */
    @RequestMapping("/tx/{userId}/{pwd}/{money}")
    @ResponseBody
    public String tx(@PathVariable int userId,@PathVariable String pwd,@PathVariable float money){
        UserInfo userInfo=userInfoService.userInfoList(userId);
        if(!userInfo.getPayPwd().equals(pwd)){
            return "1";
        }

        userInfo.setMoney(userInfo.getMoney()-money);
        userInfoService.update(userInfo);
        //资金记录
        Fund fund = new Fund();
        fund.setFundAmunt(money);
        fund.setUId(userId);
        fund.setFundPost(MoneyFund.FUND_DEPOSIT);//提现
        fundService.insert(fund);
        return "0";
    }

    /**
     * @description 兑换历史
     * @author jerry
     * @date 2020/6/17 8:29
     * @params []
     * @return java.lang.String
     */
    @GetMapping(value = "/changeHistory")
    public String changeHistory() {
        return "userInfo/changeHistory";
    }



    /***
     * @description 发送手机验证码
     * @author jerry
     * @date 2020/6/18 9:42
     * @params [phone, principal]
     * @return java.lang.String
     */
    @RequestMapping("/phoneYzm/{phone}")
    @ResponseBody
    public String phoneYzm(@PathVariable String phone,Principal principal){
        User user = loginService.queryByPhone(phone);//查询数据库是否已经存在手机号
        if(user !=null){
            return "2";
        }else {
            try {
                SmsConfig smsUtils = new SmsConfig();
                String telphoneString = phone;
                smsUtils.sendSms(telphoneString);
            } catch (ClientException e) {
                e.printStackTrace();
            }
            String code = String.valueOf((int)((Math.random()*9+1)*100000));
            String message = verificationCodeUtil.sendCode(phone, VerificationCodeUtil.ALI_TEMPLATE_CHANGE_PHONE, code);
            if ("OK".equals(message)) {
                redisUtil.set("yzm:"+principal.getName(),SmsConfig.getCode(),60*10);
            } else {
                System.out.println("message = " + message);
                return "1";
            }
            return "0";
        }

    }

    /***
     * @description 校验验证码
     * @author jerry
     * @date 2020/6/18 10:36
     * @params [yzm, principal]
     * @return java.lang.String
     */

    @RequestMapping("/checkYzm/{yzm}/{phone}")
    @ResponseBody
    public String checkYzm(@PathVariable Integer yzm,@PathVariable String phone, Principal principal){
        Integer yz = (Integer) redisUtil.get("yzm:" + principal.getName());

        int userId = loginService.queryByPhone(principal.getName()).getId();//用户id
        if(yz==null){//过期
            return "2";
        }else if(!yzm.equals(yz)){//不等于
            return "1";
        }
        User user = new User();
        user.setId(userId);
        user.setPhone(phone);
        userService.update(user);
        return "0";

    }

    /***
     * @description 身份证认证
     * @author jerry
     * @date 2020/6/19 8:42
     * @params []
     * @return java.lang.String
     */
    @RequestMapping("/cardSz/{card}/{userId}")
    @ResponseBody
    public String cardSz(@PathVariable String card,@PathVariable int userId){
        UserInfo userInfo = new UserInfo();
        User user = new User();
        String substring = card.substring(16, 17);
        if(substring.equals("1")|| substring.equals("3") || substring.equals("5") || substring.equals("5") || substring.equals("9")  ){
            user.setId(userId);
            user.setSex("男");
        }else if(substring.equals("2")|| substring.equals("4") || substring.equals("6") || substring.equals("8")  ){
            user.setId(userId);
            user.setSex("女");
        }

        userInfo.setIdCard(card);
        userInfo.setUId(userId);
        userService.update(user);
        userInfoService.updateUid(userInfo);
        return "0";
    }

    /***
     * @description 真实姓名更改
     * @author jerry
     * @date 2020/6/23 8:12
     * @params [real, userId]
     * @return java.lang.String
     */
    @RequestMapping("/realSz/{real}/{userId}")
    @ResponseBody
    public String real(@PathVariable String real,@PathVariable int userId){
        UserInfo userInfo = new UserInfo();
        userInfo.setRealName(real);
        userInfo.setUId(userId);
        userInfoService.updateUid(userInfo);
        return "0";
    }

    /***
     * @description 更改交易密码
     * @author jerry
     * @date 2020/6/19 10:24
     * @params [pwd, userId]
     * @return java.lang.String
     */
    @RequestMapping("/pwdSz/{pwd}/{userId}")
    @ResponseBody
    public String pwdSz(@PathVariable String pwd,@PathVariable int userId){
        UserInfo userInfo = new UserInfo();
        userInfo.setPayPwd(pwd);
        userInfo.setUId(userId);
        userInfoService.updateUid(userInfo);
        return "0";
    }
    /***
     * @description qq邮箱发送
     * @author jerry
     * @date 2020/6/17 20:50
     * @params [em, principal]
     * @return java.lang.String
     */
    @RequestMapping("/email/{em}")
    @ResponseBody
    public String email(@PathVariable String em,Principal principal)  {
        int userId = loginService.queryByPhone(principal.getName()).getId();//用户id

        User user = loginService.queryByMail(em);
        User user1 =userService.queryById(userId);

        if(user !=null){
            return "2";
        }else {
            //一个复杂的邮件 (也可以从一些文件里获取邮件内容)
            MimeMessage mimeMessage  = javaMailSender.createMimeMessage();
            //组装
            MimeMessageHelper helper = null;//true开启多文件
            String token = StringUtil.deleteAny(UUID.randomUUID().toString(),"-");
            redisUtil.set("email:"+userId,token,60*10);
            try {
                helper = new MimeMessageHelper(mimeMessage,true);
                //主题
                helper.setSubject("叮叮金融邮箱绑定通知");
                String uri = "http://localhost:8080";
                helper.setText("" +
                        "<!DOCTYPE html >\n" +
                        "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                        "<head>\n" +
                        "    <title>绑定邮箱</title>\n"+
                        "  <style>\n" +
                        "        .nav{ width:1200px; margin:0 auto; height:100px;}\n" +
                        "        .nav_logo{ float:left; width:468px; height:65px; margin-top:20px}\n" +
                        "         ul li{list-style:none}"+
                        "         ul.nav_navs{ float:right; height:50px; margin-top:20px;}\n" +
                        "         ul.nav_navs li{ float:left; width:80px; margin-right:20px;height:50px; line-height:50px; text-align:center; font-size:18px; color:#6d6e71;}\n" +
                        "         ul.nav_navs li.on{ border-bottom:2px solid #41aff5}\n" +
                        "         ul.nav_navs li:hover{border-bottom:2px solid #41aff5}\n" +
                        "    </style>"+
                        "</head>\n" +
                        "<body>\n" +
                        "<div style=\"background-color: white;width: 100%\">\n" +
                        "    <div class=\"nav\">\n" +
                        "        <div class=\"nav_logo\"><img style=\"width: 245px;margin-top: -10px;\" src="+uri+"/img/new-logo.png"+"></div>\n" +
                        "        <ul class=\"nav_navs\">\n" +
                        "            <a href="+uri+"/index"+"><li>首  页</li></a>\n" +
                        "            <a href="+uri+"/newGuider"+"><li>新手引导</li></a>\n" +
                        "            <a href="+uri+"/specimens/toMytz"+"><li>我要投资</li></a>\n" +
                        "            <a href="+uri+"/loan/main"+"><li>我要借款</li></a>\n" +
                        "            <a href="+uri+"/userInfo"+"><li>我的帐户</li></a>\n" +
                        "        </ul>\n" +
                        "    </div>\n" +
                        "</div>\n" +
                        "    <center>\n" +
                        "        <h2>尊敬的"+user1.getNickName()+",你好!</h2>\n" +
                        "           <h2><a href='http://localhost:8080/bindingEmail?email="+em+"&userId="+userId+"&token="+token+"'>点击此处绑定邮箱</a></h2>" +
                        "               <h3>(链接五分钟内有效)</h3>"+
                        "    </center>\n" +
                        "</body>\n" +
                        "</html>",true);
                helper.setFrom(new InternetAddress("1215207121@qq.com", "叮叮金融", "UTF-8"));
                helper.setTo(em);
                javaMailSender.send(mimeMessage);
            } catch (Exception e) {
                return "1";
            }
            return "0";
        }

    }

    /****
     * @description QQ邮箱验证
     * @author jerry
     * @date 2020/6/17 20:50
     * @params [email, userId]
     * @return java.lang.String
     */
    @RequestMapping("/bindingEmail")
    public String bindingEmail(String email,int userId,String token,Model model) throws IOException {
        String t = (String) redisUtil.get("email:" + userId);
        if(t==null){//过期
            model.addAttribute("tokenCW","令牌已过期,请重新绑定");
            return "userInfo/qqEmail";
        }
        if(!t.equals(token)){//令牌错误
            model.addAttribute("tokenCW","令牌错误,请重新绑定");
            return "userInfo/qqEmail";
        }
        User user = new User();
        user.setId(userId);
        user.setEmail(email);
        userService.update(user);
        //绑定成功后删除键
        redisUtil.del("email:"+userId);
        return "redirect:/userSet";
    }
    /****
     * @description 邮箱令牌错误跳转的页面
     * @author jerry
     * @date 2020/6/18 15:42
     * @params [model]
     * @return java.lang.String
     */
    @RequestMapping("/qqEmail")
    public String qqEmail(Model model){
        model.addAttribute("tokenCW","令牌错误,请重新绑定");
        return "userInfo/qqEmail";
    }



    /****
     * @description 支付宝接口
     * @author jerry
     * @date 2020/6/17 20:51
     * @params [userId, money, response, request, session]
     * @return void
     */
    @RequestMapping("/pay")
    public void payMent(Float money, HttpServletResponse response, HttpServletRequest request) throws IOException, AlipayApiException {
        alipayService.aliPay(response,request,money);
    }
    /**
     * @description 支付结果异步通知
     * @author norman
     * @date 2020/6/23 15:21
     * @params [session, out_trade_no]
     * @return java.lang.String
     */
    @RequestMapping("/paySuccess")
    public String paySuccess(String out_trade_no, Principal principal) throws AlipayApiException {
        User user = loginService.queryByPhone(principal.getName());

        AlipayTradeQueryResponse response = alipayService.selPayStatus(out_trade_no);
        Float money = Float.valueOf(response.getTotalAmount());
        String orderStatus = response.getTradeStatus();

        if ("WAIT_BUYER_PAY".equals(orderStatus)) {
            //交易创建，等待买家付款
        } else if ("TRADE_CLOSED".equals(orderStatus)) {
            //未付款交易超时关闭，或支付完成后全额退款
        } else if ("TRADE_SUCCESS".equals(orderStatus)) {
            //交易支付成功
            UserInfo userInfo =  userInfoService.userInfoList(user.getId());
            userInfo.setMoney(userInfo.getMoney()+money);
            userInfoService.update(userInfo);

            //资金记录
            Fund fund = new Fund();
            fund.setFundAmunt(money);
            fund.setUId(user.getId());
            fund.setFundPost(MoneyFund.FUND_RECHARGE);//充值
            fund.setOrderNumber(out_trade_no);
            fundService.insert(fund);

        } else if ("TRADE_FINISHED".equals(orderStatus)) {
            //交易结束，不可退款
        }
        return "redirect:/userInfo";
    }


}
